<template>
  <view class="energy-advice-page">
    <view class="extra-energy">
      <view class="card-title">
        <view class="title-text">闲时用电量</view>
        <image
          src="/static/img/consolePages/half-tang.png"
          mode="widthFix"
          class="half-tang"
          @click="mygo('/pages/consolePages/aiChat')"
        ></image>
      </view>
      <view class="ucharts-container">
        <view class="set-extraTime">
          <view class="set-extraTime-txt">设置闲时用电时段</view>
          <view class="time-range-section">
            <view class="time-input-group">
              <text class="time-input" @click="openTimePicker('start')">
                {{ extraStartTime || '开始时间' }}
              </text>
              <image
                class="time-icon"
                src="/static/img/components/clock-icon.png"
                mode="widthFix"
              />
            </view>
            <view class="time-input-group">
              <text class="time-input" @click="openTimePicker('end')">
                {{ extraEndTime || '结束时间' }}
              </text>
              <image
                class="time-icon"
                src="/static/img/components/clock-icon.png"
                mode="widthFix"
              />
            </view>
          </view>
        </view>
        <view class="ucharts-header">
          <view class="chart-header-container">
            <view class="chart-header-title legend-text">用电量（kwh）</view>
            <!-- 时间选择器 -->
            <view class="time-selector">
              <view
                v-for="(period, index) in timePeriods"
                :key="period.key"
                :class="['time-tab', { active: selectedPeriod === index }]"
                @click="onPeriodChange(index)"
              >
                <text class="time-text">{{ period.name }}</text>
              </view>
            </view>
          </view>
        </view>
        <view class="ucharts-content">
          <!-- 使用 swiper 组件 -->
          <tn-swiper
            v-model="currentSwiperIndex"
            :data="chartDataList"
            :height="swiperHeight + 'rpx'"
            :indicator="false"
            :autoplay="false"
            :loop="false"
            @change="handleSwiperChange"
          >
            <template #default="{ data: chartData, index: chartIndex }">
              <view class="chart-item">
                <!-- 图表 -->
                <view class="chart-container">
                  <view v-if="!isIdleTimeSet" class="no-data-tip">
                    <text class="no-data-text">请先设置闲时用电时段</text>
                  </view>
                  <view v-else-if="isLoading" class="no-data-tip">
                    <text class="no-data-text">数据加载中...</text>
                  </view>
                  <view v-else-if="chartData.categories.length === 0" class="no-data-tip">
                    <text class="no-data-text">暂无数据</text>
                  </view>
                  <qiun-data-charts
                    v-else
                    type="column"
                    :opts="chartData.chartOpts || getChartOpts(chartData.colors)"
                    :chartData="chartData"
                    :animation="false"
                  />
                </view>
                <!-- 提示文本 -->
                <view class="tips" v-if="isIdleTimeSet && !isLoading && chartData.categories.length > 0">
                  <text class="tips-text">
                    如果关停待机电器，可节约用电量{{
                      chartData.savings
                    }}kwh，
                    <text class="calc-link" @click="goToElectricityCalc">点击去计算电费</text>
                  </text>
                </view>
              </view>
            </template>
          </tn-swiper>
        </view>
      </view>
    </view>
    <view class="public-setting">
      <view class="card-title">
        <view class="title-text">公共区域节能</view>
      </view>
      <view class="card-content">
        <!-- 选择要添加的公共区域 -->
        <view class="setting-section">
          <view class="section-title">选择要添加的公共区域</view>
          <view class="area-selector" @click="openAreaPicker">
            <text class="area-display">{{
              selectedArea || '请选择公共区域'
            }}</text>
            <image
              class="arrow-icon"
              src="/static/img/components/arrow-down.png"
              mode="widthFix"
            />
          </view>
        </view>

        <!-- 设置开关时间 -->
        <view class="setting-section">
          <view class="section-header">
            <text class="section-title">设置开关时间</text>
            <tn-switch
              v-model="smartDesign"
              @change="onSmartDesignChange"
              active-color="rgba(30, 200, 225,0.6)"
              inactive-color="rgba(255, 255, 255, 0.1)"
              size="lg"
              inactive-text="智能设计"
              custom-class="smart-design-switch"
            />
          </view>

          <!-- 时段选择 -->
          <view class="time-range-section" :class="{ disabled: smartDesign }">
            <view class="time-input-group">
              <text class="time-input" @click="openSwitchTimePicker('start')">
                {{ switchStartTime || '开始时间' }}
              </text>
              <image
                class="time-icon"
                src="/static/img/components/clock-icon.png"
                mode="widthFix"
              />
            </view>
            <view class="time-input-group">
              <text class="time-input" @click="openSwitchTimePicker('end')">
                {{ switchEndTime || '结束时间' }}
              </text>
              <image
                class="time-icon"
                src="/static/img/components/clock-icon.png"
                mode="widthFix"
              />
            </view>
          </view>
        </view>

        <!-- 确认按钮 -->
        <view class="confirm-section">
          <button class="confirm-btn" @click="handleConfirm">确认</button>
        </view>
      </view>
      <view class="list-cotainer">
        <!-- 提示文本 -->
        <view class="list-header">
          <text class="list-title">公共区域开关设置全览</text>
        </view>

        <!-- 列表内容 -->
        <view class="list-content">
          <view class="list-table">
            <!-- 表头 -->
            <view class="table-header">
              <view class="header-cell area-cell">区域</view>
              <view class="header-cell time-cell">开启时间</view>
              <view class="header-cell time-cell">关闭时间</view>
              <view class="header-cell switch-cell">智能设计</view>
            </view>

            <!-- 表体 -->
            <view class="table-body">
              <view
                v-for="(item, index) in areaSettingsList"
                :key="index"
                class="table-row"
              >
                <view class="body-cell area-cell">{{ item.area }}</view>
                <view class="body-cell time-cell">{{ item.startTime }}</view>
                <view class="body-cell time-cell">{{ item.endTime }}</view>
                <view class="body-cell switch-cell">
                  <tn-switch
                    v-model="item.smartDesign"
                    active-color="rgba(30, 200, 225,0.6)"
                    inactive-color="rgba(255, 255, 255, 0.1)"
                    size="sm"
                    :before-change="
                      newValue => beforeListItemSwitchChange(item, index)
                    "
                  />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 时间选择器 -->
    <tn-date-time-picker
      v-model="tempTime"
      v-model:open="showTimePicker"
      mode="timeNoSecond"
      format="HH:mm"
      :showCancel="false"
      @confirm="onTimeConfirm"
      confirm-color="#eee"
    />

    <!-- 开关时间选择器 -->
    <tn-date-time-picker
      v-model="switchTempTime"
      v-model:open="showSwitchTimePicker"
      mode="timeNoSecond"
      format="HH:mm"
      :showCancel="false"
      @confirm="onSwitchTimeConfirm"
      confirm-color="#eee"
    />

    <!-- 区域选择器 -->
    <tn-picker
      v-model:open="showAreaPicker"
      :data="areaPickerData"
      :model-value="areaValue"
      :immediate-change="false"
      :mask="true"
      :show-cancel="false"
      confirm-color="#1ec8e1"
      label-key="label"
      value-key="value"
      @confirm="onAreaConfirm"
    />
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick, watch, computed } from 'vue';
import { mygo } from '@/utils/useNavigator';
import { createRequest } from '@/utils/request';

// 闲时用电时段
const extraStartTime = ref('');
const extraEndTime = ref('');

// 时间选择器
const showTimePicker = ref(false);
const tempTime = ref('');
const timePickerWhich = ref('start'); // start/end

// 时间选择器
const timePeriods = [
  { name: '上周', key: 'lastWeek' },
  { name: '上月', key: 'lastMonth' },
  { name: '上季', key: 'lastQuarter' },
];
const selectedPeriod = ref(0);

// swiper 相关数据
const currentSwiperIndex = ref(0);
const swiperHeight = ref(600);

// 图表数据列表（对应三个时间段）
const chartDataList = ref([
  {
    // 上周数据 - 绿色渐变主题
    categories: [],
    series: [
      {
        name: '用电量',
        data: [],
        format: function (val) {
          return val;
        },
        style: {
          opacity: 1,
        },
      },
    ],
    savings: 0, // 可节约用电量
    colors: ['#2ed573', '#1abc9c'], // 绿色渐变
    chartOpts: null, // 动态图表配置
    interval: 'lastWeek', // 新增：标识时间段
    lastFetchTime: 0, // 新增：最后获取时间戳
  },
  {
    // 上月数据 - 蓝色渐变主题
    categories: [],
    series: [
      {
        name: '用电量',
        data: [],
        format: function (val) {
          return val;
        },
        style: {
          opacity: 1,
        },
      },
    ],
    savings: 0, // 可节约用电量
    colors: ['#3498db', '#2980b9'], // 蓝色渐变
    chartOpts: null, // 动态图表配置
    interval: 'lastMonth', // 新增：标识时间段
    lastFetchTime: 0, // 新增：最后获取时间戳
  },
  {
    // 上季数据 - 橙色渐变主题
    categories: [],
    series: [
      {
        name: '用电量',
        data: [],
        format: function (val) {
          return val;
        },
        style: {
          opacity: 1,
        },
      },
    ],
    savings: 0, // 可节约用电量
    colors: ['#f39c12', '#e67e22'], // 橙色渐变
    chartOpts: null, // 动态图表配置
    interval: 'lastQuarter', // 新增：标识时间段
    lastFetchTime: 0, // 新增：最后获取时间戳
  },
]);

// 检查闲时用电时段是否已设置
const isIdleTimeSet = computed(() => {
  return extraStartTime.value && extraEndTime.value;
});

// 加载状态
const isLoading = ref(false);

// 获取图表配置的函数
const getChartOpts = (colors = ['#2ed573']) => {
  return {
    color: colors,
    padding: [30, 30, 30, 30],
    enableScroll: false,
    legend: {
      show: false,
    },
    xAxis: {
      disableGrid: true,
      fontColor: 'rgba(255, 255, 255, 0.3)',
      fontSize: 16,
      rotateLabel: false,
      boundaryGap: true,
      data: [{ min: 0, max: 7 }], // 动态设置
      labelCount: 7, // 动态设置
      itemCount: 7, // 动态设置
    },
    yAxis: {
      gridType: 'solid',
      dashLength: 0,
      fontColor: 'rgba(255, 255, 255, 0.3)',
      fontSize: 16,
      gridColor: 'rgba(255, 255, 255, 0.2)',
      splitNumber: 4,
      data: [{ min: 0, max: 1000 }], // 动态设置
    },
    extra: {
      column: {
        width: 12,
        linearType: 'custom',
        barBorderRadius: [4, 4, 0, 0],
        customColor: colors, // 使用传入的颜色数组作为渐变色
        linearOpacity: 0.6, // 渐变透明度
      },
    },
    dataLabel: true,
    dataPointShape: false,
    enableMarkLine: false,
    enableMarkPoint: false,
  };
};

// 获取闲时用电数据
const fetchIdlePowerData = async (periodKey) => {
  try {
    // 检查闲时用电时段是否已设置
    if (!isIdleTimeSet.value) {
      console.log('闲时用电时段未设置，跳过数据请求');
      return null;
    }

    const result = await createRequest('/monitor/idlePower', {
      method: 'post',
      data: {
        startTime: extraStartTime.value,
        endTime: extraEndTime.value,
        interval: periodKey
      }
    });

    if (result.code === 200 && result.data) {
      // 调整数据结构：后端返回的数据多了一层 data 嵌套
      return {
        ...result.data,
        interval: periodKey // 确保返回数据包含 interval
      };
    } else {
      console.warn('API返回错误:', result.msg);
      return null;
    }
  } catch (error) {
    console.error('获取闲时用电数据失败:', error);
    uni.showToast({
      title: '获取数据失败，请重试',
      icon: 'none'
    });
    return null;
  }
};

// 处理图表数据
const processChartData = (data, periodKey, chartIndex) => {
  // 验证数据结构和 interval 匹配
  if (!data || !data.data || !data.data.idlePowerData || data.interval !== periodKey) {
    console.warn('数据结构不匹配或 interval 不匹配:', data);
    return;
  }

  const idlePowerData = data.data.idlePowerData;
  const entries = Object.entries(idlePowerData);
  
  if (entries.length === 0) {
    console.warn('没有数据可显示');
    return;
  }

  let categories = [];
  let seriesData = [];

  // 根据时间段处理数据
  if (periodKey === 'lastWeek') {
    // 上周数据：按天显示
    categories = entries.map(([key]) => {
      const date = new Date(key);
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return weekdays[date.getDay()];
    });
    
    seriesData = entries.map(([, value]) => Math.round(parseFloat(value) || 0));
    
  } else if (periodKey === 'lastMonth') {
    // 上月数据：按周显示
    categories = entries.map(([key]) => {
      const date = new Date(key);
      return `第${Math.ceil(date.getDate() / 7)}周`;
    });
    
    seriesData = entries.map(([, value]) => Math.round(parseFloat(value) || 0));
    
  } else if (periodKey === 'lastQuarter') {
    // 上季数据：按月显示
    categories = entries.map(([key]) => {
      const date = new Date(key);
      return `${date.getMonth() + 1}月`;
    });
    
    seriesData = entries.map(([, value]) => Math.round(parseFloat(value) || 0));
  }

  // 更新图表数据
  chartDataList.value[chartIndex].categories = categories;
  chartDataList.value[chartIndex].series[0].data = seriesData;
  chartDataList.value[chartIndex].savings = Math.round(data.data.totalSavingPower || 0);
  chartDataList.value[chartIndex].lastFetchTime = Date.now(); // 记录获取时间

  // 动态设置y轴
  const maxValue = Math.max(...seriesData);
  const minValue = Math.min(...seriesData);
  const range = maxValue - minValue;
  
  // 获取当前图表的配置
  const currentChartOpts = getChartOpts(chartDataList.value[chartIndex].colors);
  
  if (seriesData.length > 0 && range > 0) {
    currentChartOpts.yAxis.data[0].min = 0;
    currentChartOpts.yAxis.data[0].max = Math.ceil(maxValue + range * 0.1);
  } else if (seriesData.length > 0) {
    // 如果所有值都相同，设置一个合理的范围
    currentChartOpts.yAxis.data[0].min = 0;
    currentChartOpts.yAxis.data[0].max = Math.ceil(maxValue * 1.2);
  } else {
    // 如果没有数据，设置默认范围
    currentChartOpts.yAxis.data[0].min = 0;
    currentChartOpts.yAxis.data[0].max = 1000;
  }

  // 设置x轴
  currentChartOpts.xAxis.data[0].min = 0;
  currentChartOpts.xAxis.data[0].max = Math.max(0, categories.length - 1);
  
  // 根据数据量智能设置标签显示数量
  const dataLength = categories.length;
  const displayCount = Math.min(dataLength, 12);
  currentChartOpts.xAxis.labelCount = displayCount;
  currentChartOpts.xAxis.itemCount = displayCount;

  // 更新图表配置
  chartDataList.value[chartIndex].chartOpts = currentChartOpts;
};

// 获取当前选中时间段的数据
const fetchCurrentPeriodData = async (forceRefresh = false) => {
  if (!isIdleTimeSet.value) {
    console.log('闲时用电时段未设置，跳过数据请求');
    return;
  }

  const currentPeriodKey = timePeriods[selectedPeriod.value]?.key;
  if (!currentPeriodKey) return;

  // 检查是否已有数据，如果没有数据或强制刷新才请求
  const currentChartData = chartDataList.value[selectedPeriod.value];
  if (!forceRefresh && currentChartData && currentChartData.categories.length > 0) {
    console.log('当前时间段已有数据，跳过请求');
    return;
  }

  isLoading.value = true;
  
  try {
    const data = await fetchIdlePowerData(currentPeriodKey);
    if (data) {
      // 根据返回的 interval 找到对应的图表索引
      const targetIndex = chartDataList.value.findIndex(item => item.interval === data.interval);
      if (targetIndex !== -1) {
        processChartData(data, data.interval, targetIndex);
        console.log(`成功处理 ${data.interval} 时间段的数据，更新图表索引: ${targetIndex}`);
      } else {
        console.warn(`未找到匹配的图表索引，interval: ${data.interval}`);
      }
    }
  } finally {
    isLoading.value = false;
  }
};

// swiper 变化事件处理
const handleSwiperChange = (index) => {
  selectedPeriod.value = index;
  const periodName = timePeriods[index]?.name || '未知';
  console.log('Swiper切换到时间段:', periodName, '索引:', index);
  
  updateSwiperHeight();
};

// 时间选择变化处理函数
const onPeriodChange = async (index) => {
  if (index === selectedPeriod.value) return;
  
  selectedPeriod.value = index;
  currentSwiperIndex.value = index;
  
  const periodName = timePeriods[index]?.name || '未知';
  console.log('时间选择器切换到时间段:', periodName, '索引:', index);
  
  // 切换时间段后立即请求数据（不强制刷新，让函数自己判断）
  await fetchCurrentPeriodData();
  
  updateSwiperHeight();
};

// 组件挂载时初始化
onMounted(() => {
  // 初始化 swiper 高度
  updateSwiperHeight();
  // 获取区域数据
  fetchAreaData();
  // 获取区域设置列表数据
  fetchAreaSettingsList();
});

// 监听闲时用电时段变化
watch([extraStartTime, extraEndTime], async ([newStartTime, newEndTime]) => {
  if (newStartTime && newEndTime) {
    // 验证时间格式
    const timeRegex = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;
    if (!timeRegex.test(newStartTime) || !timeRegex.test(newEndTime)) {
      console.warn('时间格式不正确');
      return;
    }
    
    console.log('闲时用电时段已设置，开始获取数据');
    // 用电时段变化时，强制刷新数据
    await fetchCurrentPeriodData(true);
  }
}, { immediate: false });

// 跳转到电费计算页面
const goToElectricityCalc = () => {
  mygo('/pages/consolePages/ElectricityCalc');
};

// 获取区域数据
async function fetchAreaData() {
  try {
    // TODO: 调用后端接口获取公共区域数据
    // const res = await createRequest('/api/public-areas', { method: 'GET' });
    // areaPickerData.value = res.data;

    // 模拟数据 - 公共区域级联选择数据
    areaPickerData.value = [
      {
        label: '现场校区',
        value: '现场校区',
        children: [
          {
            label: 'A区',
            value: 'a',
            children: [
              { label: 'A1栋', value: 'a1' },
              { label: 'A2栋', value: 'a2' },
              { label: 'A3栋', value: 'a3' },
            ],
          },
          {
            label: 'B区',
            value: 'b',
            children: [
              { label: 'B1栋', value: 'b1' },
              { label: 'B2栋', value: 'b2' },
            ],
          },
        ],
      },
      {
        label: '高新区校区',
        value: 'gaoxin',
        children: [
          {
            label: '宿舍楼',
            value: 'sushe',
            children: [
              { label: '1号楼', value: 'sushe1' },
              { label: '2号楼', value: 'sushe2' },
            ],
          },
          {
            label: '食堂',
            value: 'shitang',
            children: [
              { label: '一楼食堂', value: 'shitang1' },
              { label: '二楼食堂', value: 'shitang2' },
            ],
          },
        ],
      },
    ];
  } catch (error) {
    console.error('获取公共区域数据失败:', error);
    uni.showToast({ title: '获取公共区域数据失败', icon: 'none' });
  }
}

// 监听 swiper 索引变化，确保时间选择器同步
watch(currentSwiperIndex, newIndex => {
  if (selectedPeriod.value !== newIndex) {
    selectedPeriod.value = newIndex;
  }
});

// 监听时间选择器变化，确保 swiper 同步
watch(selectedPeriod, newIndex => {
  if (currentSwiperIndex.value !== newIndex) {
    currentSwiperIndex.value = newIndex;
  }
});

// 更新 swiper 高度
const updateSwiperHeight = () => {
  nextTick(() => {
    if (chartDataList.value.length === 0) {
      swiperHeight.value = 600;
      return;
    }

    const currentChartData = chartDataList.value[currentSwiperIndex.value];
    if (currentChartData) {
      // 根据图表数据动态调整高度
      const chartHeight = 500; // 图表固定高度
      
      // 只有当有数据时才显示tips区域
      const shouldShowTips = isIdleTimeSet.value && !isLoading.value && currentChartData.categories.length > 0;
      const tipsHeight = shouldShowTips ? 100 : 0; // 提示文本高度
      const totalHeight = chartHeight + tipsHeight;

      // 考虑 transform scale 的影响
      const scaleFactor = 0.95;
      swiperHeight.value = Math.round(totalHeight * scaleFactor);
    } else {
      swiperHeight.value = 600; // 默认高度
    }
  });
};

// 打开时间选择器
function openTimePicker(which) {
  timePickerWhich.value = which;

  // 设置当前时间值
  tempTime.value =
    which === 'start' ? extraStartTime.value : extraEndTime.value;

  showTimePicker.value = true;
}

// 时间选择器确认
function onTimeConfirm(val) {
  setTimeValue(val);
  showTimePicker.value = false;
}

// 设置时间值
function setTimeValue(timeVal) {
  if (timePickerWhich.value === 'start') {
    extraStartTime.value = timeVal;
  } else {
    extraEndTime.value = timeVal;
  }
}

// 公共区域节能相关数据
const selectedArea = ref('');
const smartDesign = ref(false);
const switchStartTime = ref('');
const switchEndTime = ref('');

// 区域设置列表数据
const areaSettingsList = ref([]);

// 区域选择器
const showAreaPicker = ref(false);
const areaValue = ref([]);
const areaPickerData = ref([]);

// 开关时间选择器
const showSwitchTimePicker = ref(false);
const switchTempTime = ref('');
const switchTimePickerWhich = ref('start'); // start/end

// 打开区域选择器
function openAreaPicker() {
  showAreaPicker.value = true;
}

// 区域选择确认
function onAreaConfirm(val) {
  // 级联选择返回的是数组，取最后一个值作为选中的区域
  const selectedAreaValue = Array.isArray(val) ? val[val.length - 1] : val;

  // 格式化显示文本
  selectedArea.value = formatAreaDisplay(val);
  areaValue.value = Array.isArray(val) ? val : [val];

  showAreaPicker.value = false;
}

// 格式化区域显示文本（支持多级）
function formatAreaDisplay(values) {
  if (!values || values.length === 0) return '';

  // 根据级联路径查找对应的标签
  const labels = [];
  let currentLevel = areaPickerData.value;

  for (const value of values) {
    const item = currentLevel.find(item => item.value === value);
    if (item) {
      labels.push(item.label);
      currentLevel = item.children || [];
    } else {
      break;
    }
  }

  // 格式化显示文本
  if (labels.length === 0) return '';
  if (labels.length === 1) return labels[0];
  if (labels.length === 2) return `${labels[0]}—${labels[1]}`;
  if (labels.length === 3) return `${labels[0]}—${labels[1]}—${labels[2]}`;
  // 支持更多层级
  return labels.join('—');
}

// 智能设计开关变化
function onSmartDesignChange(value) {
  console.log('智能设计开关状态:', value);
}

// 打开开关时间选择器
function openSwitchTimePicker(which) {
  if (smartDesign.value) return; // 如果智能设计开启，禁用时间选择

  switchTimePickerWhich.value = which;

  // 设置当前时间值
  switchTempTime.value =
    which === 'start' ? switchStartTime.value : switchEndTime.value;

  showSwitchTimePicker.value = true;
}

// 开关时间选择器确认
function onSwitchTimeConfirm(val) {
  setSwitchTimeValue(val);
  showSwitchTimePicker.value = false;
}

// 设置开关时间值
function setSwitchTimeValue(timeVal) {
  if (switchTimePickerWhich.value === 'start') {
    switchStartTime.value = timeVal;
  } else {
    switchEndTime.value = timeVal;
  }
}

// 确认按钮处理
function handleConfirm() {
  if (!selectedArea.value || areaValue.value.length === 0) {
    uni.showToast({ title: '请选择公共区域', icon: 'none' });
    return;
  }

  if (!smartDesign.value && (!switchStartTime.value || !switchEndTime.value)) {
    uni.showToast({ title: '请设置开关时间', icon: 'none' });
    return;
  }

  // 构建提交数据
  const submitData = {
    area: selectedArea.value,
    areaValue: areaValue.value, // 包含完整的级联路径
    smartDesign: smartDesign.value,
    startTime: switchStartTime.value,
    endTime: switchEndTime.value,
  };

  console.log('提交数据:', submitData);

  // TODO: 调用后端接口
  // createRequest('/api/public-area-setting', { method: 'POST', data: submitData })
  //   .then(res => {
  //     uni.showToast({ title: '设置成功', icon: 'success' });
  //   })
  //   .catch(err => {
  //     uni.showToast({ title: '设置失败', icon: 'none' });
  //   });

  // 模拟成功
  uni.showToast({ title: '设置成功', icon: 'success' });
}

// 获取区域设置列表数据
async function fetchAreaSettingsList() {
  try {
    // TODO: 调用后端接口获取区域设置列表数据
    // const res = await createRequest('/api/area-settings-list', { method: 'GET' });
    // areaSettingsList.value = res.data;

    // 模拟数据 - 区域设置列表数据
    areaSettingsList.value = [
      {
        id: 1,
        area: '一级区域二级区域三级区域',
        startTime: '7:00',
        endTime: '11:00',
        smartDesign: false,
      },
      {
        id: 2,
        area: '一级区域二级区域三级区域',
        startTime: '7:00',
        endTime: '11:00',
        smartDesign: true,
      },
      {
        id: 3,
        area: '一级区域二级区域三级区域',
        startTime: '7:00',
        endTime: '11:00',
        smartDesign: false,
      },
      {
        id: 4,
        area: '一级区域二级区域三级区域',
        startTime: '7:00',
        endTime: '11:00',
        smartDesign: false,
      },
      {
        id: 5,
        area: '一级区域二级区域三级区域',
        startTime: '7:00',
        endTime: '11:00',
        smartDesign: false,
      },
      {
        id: 6,
        area: '一级区域二级区域三级区域',
        startTime: '7:00',
        endTime: '11:00',
        smartDesign: false,
      },
      {
        id: 7,
        area: '一级区域二级区域三级区域',
        startTime: '7:00',
        endTime: '11:00',
        smartDesign: false,
      },
    ];
  } catch (error) {
    console.error('获取区域设置列表数据失败:', error);
    uni.showToast({ title: '获取区域设置列表数据失败', icon: 'none' });
  }
}

// 列表项开关切换处理
const beforeListItemSwitchChange = async (item, index) => {
  // 计算目标状态：用户点击后想要切换到的状态
  const targetSmartDesign = !item.smartDesign;

  try {
    // 发起请求修改状态
    // const response = await createRequest('/api/area-setting/toggle', {
    //   method: 'POST',
    //   data: {
    //     id: item.id,
    //     area: item.area,
    //     smartDesign: targetSmartDesign
    //   }
    // });

    // 模拟请求成功
    await new Promise(resolve => setTimeout(resolve, 500));

    console.log(`第${index + 1}项智能设计开关状态切换为:`, targetSmartDesign);

    // 请求成功，允许切换（组件会自动切换状态）
    return true;
  } catch (error) {
    console.error('切换智能设计状态失败:', error);

    uni.showToast({
      title: '操作失败，请重试',
      icon: 'none',
    });

    return false; // 阻止切换
  }
};
</script>

<style scoped lang="scss">
.energy-advice-page {
  padding: 20rpx;
  box-sizing: border-box;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.extra-energy {
  width: 686rpx;
}
.card-title {
  width: 686rpx;
  height: 68rpx;
  background: url('/static/img/homePages/card-title.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.title-text {
  font-size: 32rpx;
  color: #eee;
  font-weight: 500;
  margin-left: 56rpx;
  margin-top: -4rpx;
}
.half-tang {
  width: 54rpx;
  margin-right: 20rpx;
}
.ucharts-container {
  width: 100%;
  height: 824rpx;
  padding: 20rpx;
  box-sizing: border-box;
}
.set-extraTime {
  width: 100%;
  height: 100rpx;

  .set-extraTime-txt {
    font-size: 28rpx;
    color: #fff;
    margin-bottom: 16rpx;
  }
}

// 时间范围选择区域
.time-range-section {
  display: flex;
  gap: 20rpx;
  margin-top: 16rpx;
}

.time-input-group {
  flex: 1;
  position: relative;
  display: flex;
  align-items: center;
}

.time-input {
  flex: 1;
  height: 52rpx;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4rpx;
  padding: 0 24rpx;
  font-size: 24rpx;
  color: #fff;
  display: flex;
  align-items: center;
}

.time-icon {
  position: absolute;
  right: 16rpx;
  width: 20rpx;
  height: 20rpx;
  pointer-events: none;
}

.ucharts-header {
  width: 100%;
  min-height: 92rpx;
}
.chart-header-container {
  width: 100%;
  height: 86rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.chart-header-title {
  flex: 1;
  padding: 30rpx;
  box-sizing: border-box;
}
.legend-text {
  font-size: 20rpx;
  color: rgba($color: #fff, $alpha: 0.8);
}

// 时间选择器样式
.time-selector {
  flex: 1;
  display: flex;
  padding: 30rpx;
  align-items: center;
  justify-content: space-evenly;
  box-sizing: border-box;
}

.time-tab {
  flex: 1;
  text-align: center;
  transition: all 0.3s ease;
  padding: 0 8rpx;
  background-color: rgba($color: #fff, $alpha: 0.08);
  min-width: 66rpx;
  margin-right: 8rpx;
  border-radius: 4rpx;
  height: 32rpx;
  line-height: 32rpx;
  text-align: center;
  cursor: pointer;

  &:last-child {
    margin-right: 0;
  }

  &:hover {
    background-color: rgba($color: #fff, $alpha: 0.12);
  }
}

.time-tab.active {
  background-color: rgba($color: #096bda, $alpha: 0.2);
}

.time-text {
  font-size: 20rpx;
  color: rgba($color: #fff, $alpha: 0.5);
  transition: color 0.3s ease;
}

.time-tab.active .time-text {
  color: #096bda;
  font-weight: 500;
}

// 图表内容样式
.ucharts-content {
  width: 100%;
  height: 600rpx;
  position: relative;
  overflow: hidden; // 添加这行来修复swiper item间隙问题
}

.chart-item {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-container {
  flex: 1;
  width: 100%;
  height: 500rpx;
  position: relative;
  transform: scale(1.08);
  transform-origin: center center;
}

.no-data-tip {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
}

.no-data-text {
  font-size: 28rpx;
  color: rgba(255, 255, 255, 0.5);
  text-align: center;
}

.tips {
  width: 100%;
  height: 100rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

.tips-text {
  font-size: 22rpx;
  color: rgba($color: #fff, $alpha: 0.8);
  text-align: center;
  line-height: 1.5;
}

.calc-link {
  color: #1ec8e1;
  text-decoration: underline;
  cursor: pointer;
  
  &:hover {
    color: #5ebeff;
  }
}

// 公共区域节能样式
.public-setting {
  width: 686rpx;
  margin-top: 30rpx;
}

.card-content {
  width: 100%;
  min-height: 400rpx;
  padding: 30rpx;
  box-sizing: border-box;
  background: rgba(255, 255, 255, 0.05);
  border: 1rpx solid rgba(255, 255, 255, 0.1);
  border-radius: 8rpx;
  margin-top: 20rpx;
}

.setting-section {
  margin-bottom: 24rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 28rpx;
  color: #fff;
  font-weight: 500;
  margin-bottom: 12rpx;
}

.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx;
}

.area-selector {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60rpx;
  background: rgba(255, 255, 255, 0.1);
  border: 1rpx solid rgba(255, 255, 255, 0.2);
  border-radius: 4rpx;
  padding: 0 20rpx;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    background: rgba(255, 255, 255, 0.15);
  }
}

.area-display {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  flex: 1;

  &:empty::before {
    content: '请选择公共区域';
    color: rgba(255, 255, 255, 0.4);
  }
}

.arrow-icon {
  width: 16rpx;
  height: 16rpx;
  margin-left: 10rpx;
}

// 智能设计开关自定义样式
.smart-design-switch {
  // 可以自定义 switch 的样式
  // 例如：调整间距、字体大小等
  width: 220rpx;
  height: 44rpx;

  // 消除容器左右 padding，让 dot 贴边
  padding: 0 !important;

  :deep(.tn-switch__dot) {
    background-color: #8990ab;
    width: 110rpx;
    height: 44rpx;
    border-radius: 30rpx;
    // 消除左边距，让 dot 贴左边
    left: 0 !important;
  }

  :deep(.tn-switch__dot--checked) {
    // 消除右边距，让 dot 贴右边
    left: 100% !important;
  }

  :deep(.tn-switch__inactive-content--text) {
    font-size: 22rpx;
    padding: 0 0 0 54rpx;
    color: rgba(255, 255, 255, 0.5);
  }
}

// 时段选择禁用状态
.time-range-section.disabled {
  opacity: 0.5;
  pointer-events: none;
}

.time-range-section.disabled .time-input {
  background: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.4);
}

.confirm-section {
  margin-top: 40rpx;
}

.confirm-btn {
  width: 100%;
  height: 80rpx;
  background: linear-gradient(135deg, #1ec8e1 0%, #096bda 100%);
  border: none;
  border-radius: 8rpx;
  color: #fff;
  font-size: 28rpx;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2rpx);
    box-shadow: 0 8rpx 20rpx rgba(30, 200, 225, 0.3);
  }

  &:active {
    transform: translateY(0);
  }
}

// 列表容器样式
.list-cotainer {
  width: 100%;
  margin-top: 30rpx;
}

.list-header {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: -10rpx auto 10rpx;
}

.list-title {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.5);
}

.list-content {
  width: 100%;
  background: rgba(255, 255, 255, 0.05);
  border: 1rpx solid rgba(255, 255, 255, 0.1);
  border-radius: 8rpx;
  overflow: hidden;
}

.list-table {
  width: 100%;
}

// 表头样式
.table-header {
  display: flex;
  background: rgba(255, 255, 255, 0.08);
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.1);
}

.header-cell {
  padding: 20rpx 16rpx;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.8);
  font-weight: 500;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;

  &.area-cell {
    flex: 2;
    justify-content: flex-start;
  }

  &.time-cell {
    flex: 1;
  }

  &.switch-cell {
    flex: 1;
  }
}

// 表体样式
.table-body {
  max-height: 600rpx;
  overflow-y: auto;
}

.table-row {
  display: flex;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.05);
  transition: background-color 0.3s ease;

  &:hover {
    background: rgba(255, 255, 255, 0.02);
  }

  &:last-child {
    border-bottom: none;
  }
}

.body-cell {
  padding: 24rpx 16rpx;
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;

  &.area-cell {
    flex: 2;
    justify-content: flex-start;
    text-align: left;
  }

  &.time-cell {
    flex: 1;
    text-align: center;
  }

  &.switch-cell {
    flex: 1;
    justify-content: center;
  }
}
</style>
